package com.pss.order.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * standard分片策略的表精确分片算法实现类
 * 实现接口 PreciseShardingAlgorithm<T>， 泛型类T是分片键的字段类型
 */
public class TablePreciseAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     *  精确分片算法：用于处理=和IN的分片
     * @param availableTargetNames - 数据源或者实际表的名字集合
     * @param preciseShardingValue - 包含逻辑表名、分片列和分片列的值
     * @return 返回分片后的实际表名
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        //获取分片列的值
        Long value = preciseShardingValue.getValue();
        //获得虚拟表名
        String logicTableName = preciseShardingValue.getLogicTableName();
        //实现course_$->{cid%2+1} 取模分片算法
        long index = value % 2 + 1;
        //拼接获得实际表名
        String actualTableName = logicTableName + "_" + index;
        //判断配置的实际表集合中是否有该实际表名
        if(availableTargetNames.contains(actualTableName)) {
            return actualTableName;
        }
        return null;
    }
}
